Skip to content

File Drag and Drop Overwrite Prompt#1932

Merged
oneirocosm merged 5 commits intomainfrom
sylvie/drop-overwrite
Feb 10, 2025
Merged

File Drag and Drop Overwrite Prompt#1932
oneirocosm merged 5 commits intomainfrom
sylvie/drop-overwrite

Conversation

@oneirocosm
Copy link
Contributor

If a file drag and drop file fails because the file already exists, this adds a popup to allow the operation to be retried with the overwrite flag set. Additionally, it will make a similar dismissible popup to cover other copy errors.

This allows a user to retry an attempted copy if it requires the
overwrite option.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 8, 2025

Walkthrough

The changes update the file copying functionality within the directory preview component. A new type, FileCopyStatus, is defined to track details of a file copy operation, including data, error information, and whether a retry is allowed. A new state variable, copyStatus, is introduced to maintain this information. The diff also adds a handleDropCopy function that executes the file copy command and updates the state based on the operation’s result. Additionally, the CopyErrorOverlay component is implemented to display error messages and provide retry options when a file copy fails. The existing drop handling logic is updated to use the new function and components, and the changes include the use of a callback ref hook for dynamic dimension management.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
frontend/app/view/preview/directorypreview.tsx (3)

39-43: Consider extending or enumerating error handling states.
The new "FileCopyStatus" type is adequate but might benefit from distinguishing various error types or including error codes, allowing more robust handling of multiple failure scenarios.


912-931: Enhance error checking logic.
Relying on “.endsWith('overwrite not specified')” could be fragile if API error messages change. Consider a more structured approach (e.g., error codes) for robust retry checks.


963-964: Confirm complete dependency array.
If "handleDropCopy" is itself a dependency, consider adding it explicitly to align with React’s best practices, ensuring the drop callback always has the latest version of the function.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c00156c and c41e252.

📒 Files selected for processing (2)
  • frontend/app/view/preview/directorypreview.scss (1 hunks)
  • frontend/app/view/preview/directorypreview.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build for TestDriver.ai
  • GitHub Check: Analyze (go)
🔇 Additional comments (6)
frontend/app/view/preview/directorypreview.tsx (5)

5-5: Import usage looks good.
This added import for "CopyButton" is used within the new overlay. No further issues found.


7-7: Confirmed reference usage of custom hook.
The imported hook "useDimensionsWithCallbackRef" is applied properly in the overlay. No concerns.


801-801: Ensure the type accommodates null state.
While you’ve assigned null, verify that the "FileCopyStatus" type or usage pattern expects or safely handles null. You could consider using "FileCopyStatus | null" to make this safe explicitly.


958-958: Drop callback chaining is well-handled.
"handleDropCopy" is cleanly invoked upon a drop event, providing a clear flow. No issues.


1077-1083: Conditional overlay rendering is straightforward.
Displaying the "CopyErrorOverlay" when "copyStatus" is non-null is logical and succinct.

frontend/app/view/preview/directorypreview.scss (1)

203-319: Overlay styling is cohesive and responsive.
These new ".copyerror-overlay" rules appear well-structured and consistent. Keep an eye on potential performance implications of a high blur radius. Otherwise, looks good.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
frontend/app/view/preview/directorypreview.tsx (3)

39-43: Add JSDoc comments to document the type definition.

The FileCopyStatus type would benefit from documentation explaining the purpose of each field.

+/**
+ * Represents the status of a file copy operation.
+ */
 type FileCopyStatus = {
+    /** The data required for the copy operation */
     copyData: CommandFileCopyData;
+    /** Error message if the copy operation failed */
     copyError: string;
+    /** Whether the operation can be retried with overwrite flag */
     allowRetry: boolean;
 };

912-931: Improve error handling in the copy operation.

The error handling could be more robust:

  1. Consider using a more specific error type instead of converting to string directly.
  2. Add error classification to handle different types of errors differently.
 const handleDropCopy = useCallback(
     async (data: CommandFileCopyData) => {
         try {
             await RpcApi.FileCopyCommand(TabRpcClient, data, { timeout: data.opts.timeout });
             setCopyStatus(null);
         } catch (e) {
             console.log("copy failed:", e);
-            const copyError = `${e}`;
-            const allowRetry = copyError.endsWith("overwrite not specified");
+            // Classify error types
+            const copyError = e instanceof Error ? e.message : String(e);
+            const allowRetry = copyError.includes("overwrite not specified") || 
+                             copyError.includes("file exists");
             const copyStatus: FileCopyStatus = {
                 copyError,
                 copyData: data,
                 allowRetry,
             };
             setCopyStatus(copyStatus);
         }
         model.refreshCallback();
     },
     [setCopyStatus, model.refreshCallback]
 );

1135-1140: Improve error message presentation.

The error message handling could be more user-friendly and consistent.

-        let statusText = "Copy Error";
-        let errorMsg = `error: ${copyStatus?.copyError}`;
+        let statusText = copyStatus?.allowRetry ? "Confirm Overwrite" : "Copy Failed";
+        let errorMsg = copyStatus?.allowRetry
+            ? "One or more files already exist at the destination. Would you like to overwrite them?"
+            : `Failed to copy: ${copyStatus?.copyError}`;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c41e252 and 73fcb65.

📒 Files selected for processing (1)
  • frontend/app/view/preview/directorypreview.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build for TestDriver.ai
🔇 Additional comments (1)
frontend/app/view/preview/directorypreview.tsx (1)

1124-1133: Avoid direct mutation of copyData in handleRetryCopy.

The function should create a new object instead of mutating the existing one.

Comment on lines +1153 to +1158
const handleCopyToClipboard = React.useCallback(
async (e: React.MouseEvent) => {
await navigator.clipboard.writeText(errorMsg);
},
[errorMsg]
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add error handling to clipboard operations.

The clipboard operation should handle potential failures gracefully.

 const handleCopyToClipboard = React.useCallback(
-    async (e: React.MouseEvent) => {
+    async () => {
         try {
             await navigator.clipboard.writeText(errorMsg);
+        } catch (error) {
+            console.error('Failed to copy to clipboard:', error);
+            // Optionally show a user-friendly error message
         }
     },
     [errorMsg]
 );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const handleCopyToClipboard = React.useCallback(
async (e: React.MouseEvent) => {
await navigator.clipboard.writeText(errorMsg);
},
[errorMsg]
);
const handleCopyToClipboard = React.useCallback(
async () => {
try {
await navigator.clipboard.writeText(errorMsg);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
// Optionally show a user-friendly error message
}
},
[errorMsg]
);

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
frontend/app/view/preview/directorypreview.tsx (3)

912-931: Enhance error handling with specific error types and descriptive messages.

While the error handling is functional, it could be improved for better user experience and debugging.

Consider these improvements:

 async (data: CommandFileCopyData) => {
     try {
         await RpcApi.FileCopyCommand(TabRpcClient, data, { timeout: data.opts.timeout });
         setCopyStatus(null);
     } catch (e) {
-        console.log("copy failed:", e);
-        const copyError = `${e}`;
+        console.error("File copy operation failed:", e);
+        const errorMessage = e instanceof Error ? e.message : String(e);
+        const isOverwriteError = errorMessage.endsWith("overwrite not specified");
+        const copyError = isOverwriteError
+            ? "Cannot overwrite existing file without permission"
+            : `File copy failed: ${errorMessage}`;
         const allowRetry = copyError.endsWith("overwrite not specified");
         const copyStatus: FileCopyStatus = {
             copyError,
             copyData: data,
             allowRetry,
         };
         setCopyStatus(copyStatus);
     }
     model.refreshCallback();
 }

1124-1133: Optimize retry function memoization.

The retry function's dependency array could be optimized to prevent unnecessary re-renders.

 const handleRetryCopy = React.useCallback(async () => {
     if (!copyStatus) {
         return;
     }
     const updatedData = {
         ...copyStatus.copyData,
         opts: { ...copyStatus.copyData.opts, overwrite: true },
     };
     await handleDropCopy(updatedData);
-}, [copyStatus.copyData]);
+}, [copyStatus?.copyData, handleDropCopy]);

1153-1204: Enhance accessibility with ARIA labels and keyboard navigation.

The error overlay could be more accessible with proper ARIA attributes and keyboard support.

 <div
     ref={overlayRefCallback}
+    role="dialog"
+    aria-label={statusText}
+    aria-describedby="error-message"
     className="absolute top-[0] left-1.5 right-1.5 z-[var(--zindex-block-mask-inner)] overflow-hidden bg-[var(--conn-status-overlay-bg-color)] backdrop-blur-[50px] rounded-md shadow-lg"
 >
     {/* ... */}
-    <div>{errorMsg}</div>
+    <div id="error-message">{errorMsg}</div>
     {/* ... */}
     <Button
         className={buttonClassName}
+        onKeyDown={(e) => {
+            if (e.key === 'Escape') {
+                handleRemoveCopyError();
+            }
+        }}
         onClick={handleRemoveCopyError}
     >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 73fcb65 and 5950cda.

📒 Files selected for processing (1)
  • frontend/app/view/preview/directorypreview.tsx (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build for TestDriver.ai
  • GitHub Check: Analyze (go)
🔇 Additional comments (2)
frontend/app/view/preview/directorypreview.tsx (2)

39-43: LGTM! Well-structured type definition and state management.

The FileCopyStatus type effectively captures all necessary information for tracking file copy operations, and the state management is properly implemented using React's useState hook.

Also applies to: 801-801


1148-1150: Add error handling to clipboard operations.

The clipboard operation should handle potential failures gracefully.

 const handleCopyToClipboard = React.useCallback(async () => {
+    try {
         await navigator.clipboard.writeText(errorMsg);
+    } catch (error) {
+        console.error('Failed to copy to clipboard:', error);
+        // Optionally show a user-friendly error message
+    }
 }, [errorMsg]);

@oneirocosm oneirocosm merged commit 2b060eb into main Feb 10, 2025
8 checks passed
@oneirocosm oneirocosm deleted the sylvie/drop-overwrite branch February 10, 2025 23:21
xxyy2024 pushed a commit to xxyy2024/waveterm_aipy that referenced this pull request Jun 24, 2025
If a file drag and drop file fails because the file already exists, this
adds a popup to allow the operation to be retried with the overwrite
flag set. Additionally, it will make a similar dismissible popup to
cover other copy errors.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant